package info.batcloud.fanli.api.controller;

import info.batcloud.fanli.core.domain.BusinessResponse;
import info.batcloud.fanli.core.entity.FlashSaleItem;
import info.batcloud.fanli.core.enums.FlashSaleItemSort;
import info.batcloud.fanli.core.enums.FlashSaleItemStatus;
import info.batcloud.fanli.core.helper.SecurityHelper;
import info.batcloud.fanli.core.repository.FlashSaleItemRepository;
import info.batcloud.fanli.core.service.FlashSaleItemService;
import info.batcloud.fanli.core.service.UrlMappingService;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.inject.Inject;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/flash-sale-item")
public class FlashSaleItemController {

    @Inject
    private FlashSaleItemService flashSaleItemService;

    @Inject
    private FlashSaleItemRepository flashSaleItemRepository;

    @Inject
    private UrlMappingService urlMappingService;

    @GetMapping("/search")
    public Object search(FlashSaleItemService.SearchParam param) {
        param.setSort(FlashSaleItemSort.ID_DESC);
        Map<String, Object> map = new HashMap<>();
        param.setStatus(FlashSaleItemStatus.ONSALE);
        param.setFinished(false);
        param.setCheckRemindUserId(SecurityHelper.loginUserId());
        map.put("flashSaleItemPaging", flashSaleItemService.search(param));
        return BusinessResponse.ok(map);
    }

    @GetMapping("/check/draw/{id}")
    @PreAuthorize("hasRole('USER')")
    public Object checkDraw(@PathVariable long id) {
        long userId = SecurityHelper.loginUserId();
        Map<String, Object> model = new HashMap<>(1);
        model.put("helperUrl", urlMappingService.flashSaleDrawHelperUrl());
        model.put("userHasDrawn", flashSaleItemService.checkDrawn(id, userId));
        FlashSaleItem fsi = flashSaleItemRepository.findOne(id);
        model.put("itemId", fsi.getItem().getId());
        return BusinessResponse.ok(model);
    }

    @PutMapping("/draw/{id}")
    @PreAuthorize("hasRole('USER')")
    public Object draw(@PathVariable long id) {
        return BusinessResponse.ok(flashSaleItemService.draw(id, SecurityHelper.loginUserId()));
    }

}
